package me.heizi.springboot.students.security


import me.heizi.springboot.students.hexString
import me.heizi.springboot.students.repositories.UserRepository
import me.heizi.springboot.students.sha256
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.security.MessageDigest
import java.util.*
import kotlin.collections.HashMap
import kotlin.experimental.and
import kotlin.random.Random
import kotlin.system.exitProcess

/**
 * 生成Token并且保存
 * Token用于用户Cookies保存
 */
interface TokenProvider {
    fun genTokenAndSaveToken(id: Long):String
    fun auth(id:Long,token:String):Boolean
}

/**
 * 保存在内存里，Token = sha256(id+name+random+password) ,
 * save in hashmap , key is user id , value is token
 */
@Component
class DefaultTokenProvider:TokenProvider {

    val inMemory = HashMap<Long,String>()
    override fun genTokenAndSaveToken(id: Long):String {
        val sha256 = "$id${System.currentTimeMillis()}${Random.nextLong()}${Random.nextDouble()}".sha256()
        inMemory[id] = sha256
        return sha256
    }
    override fun auth(id: Long, token: String): Boolean
        = inMemory[id] == token
}
